﻿using System.ComponentModel;
using System;
using System.Windows;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Windows.Controls;
using PDO.DataPersistence.Core;


namespace PDO.FX.App
{
    /// <summary>
    /// Interaction logic for ExpressionEvaluatorPopup.xaml
    /// </summary>
    public partial class ExpressionEvaluatorPopup : Window, INotifyPropertyChanged
    {

        public ExpressionEvaluatorPopup()
        {
            InitializeComponent();
        }

        private PersistableDataObject _pdo;
        public ExpressionEvaluatorPopup(PersistableDataObject pdo)
            : this()
        {
            _pdo = pdo;
            DataContext = this;
        }


        private string _activeObjectPath;

        /// <summary>
        /// Set active property path by walking backward from end of sub-expression string till 
        /// we find the start of a property path expresson.
        /// </summary>
        /// <param name="s">expression sub-string</param>
        private void SetActiveObjectPath()
        {
            string s = GetExpression();

            if (s.EndsWith("."))
            {
                s = s.Substring(0, s.Length - 1);
            }

            char c;
            int i;
            bool inBrace = false;
            bool exitParse = false;
            for (i = s.Length - 1; exitParse == false && i > 0; i--)
            {
                c = s[i];
                switch (c)
                {
                    case ']':
                        inBrace = true;
                        break;

                    case '[':
                        if (!inBrace)
                        {
                            exitParse = true;
                        }
                        break;

                    case ' ':
                        exitParse = true;
                        break;
                }

            }

            if (i >= 0)
            {
                _activeObjectPath = s.Substring(i).Trim();
            }
            else
            {
                _activeObjectPath = string.Empty;
            }


            // Notify change to affected properties
            _intellisenseOptions = null;
            OnPropertyChanged("IntellisenseOptions");
        }


        private void OnExpressionKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            TextBox txtBox = sender as TextBox;

            if ((txtBox == null) || (txtBox.CaretIndex == 0))
            {
                return;
            }

            // Check for a predefined hot-key
            if (e.Key != System.Windows.Input.Key.OemPeriod)
                return;


            SetActiveObjectPath();

            if (IntellisenseOptions != null && IntellisenseOptions.Count() > 0)
            {
                ShowPropertiesPopup(txtBox.GetRectFromCharacterIndex(txtBox.CaretIndex, true));
            }
        }

        public string DataContextObjectName
        {
            get { return _pdo.GetType().ToString(); }
        }

        private PersistableDataObject _expressionDataContext;

        public PersistableDataObject ExpressionDataContext
        {
            get { return _expressionDataContext; }
            set { _expressionDataContext = value; }
        }

        private IEnumerable<string> _intellisenseOptions;
        public IEnumerable<string> IntellisenseOptions
        {
            get
            {
                object o;
                if (_activeObjectPath.Length > 0)
                {
                    o = ReflectionHelper.GetPropertyPathValue(_pdo, _activeObjectPath);
                }
                else
                {
                    o = _pdo;
                }

                if (null == _intellisenseOptions && o != null)
                {
                    Type type = o.GetType();

                    _intellisenseOptions = (from p in
                                                type.GetProperties(System.Reflection.BindingFlags.Public |
                                                                 System.Reflection.BindingFlags.Instance)
                                            select p.Name).ToList<string>().OrderBy(p => p);
                }

                return _intellisenseOptions;
            }
        }


        private void ShowPropertiesPopup(Rect placementRect)
        {
            _popupProperties.PlacementTarget = _expression;
            _popupProperties.PlacementRectangle = placementRect;
            _popupProperties.IsOpen = true;

            _propertySelector.SelectedIndex = 0;
            _propertySelector.Focus();
        }


        private void OnListKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            switch (e.Key)
            {
                case System.Windows.Input.Key.Tab:
                case System.Windows.Input.Key.Enter:

                    // Hide the Popup
                    _popupProperties.IsOpen = false;

                    ListBox lb = sender as ListBox;
                    if (lb == null)
                        return;

                    if (lb.SelectedItems.Count == 1)
                    {
                        // Get the selected item value
                        string methodName = lb.SelectedItem.ToString();

                        // Save the Caret position
                        int i = _expression.CaretIndex;

                        // Add text to the text
                        _expression.Text = _expression.Text.Insert(i, methodName);

                        // Move the caret to the end of the added text
                        _expression.CaretIndex = i + methodName.Length;
                    }

                    // Move focus back to the text box. 
                    // This will auto-hide the popup due to StaysOpen="false"
                    _expression.Focus();

                    e.Handled = true;

                    break;

                case System.Windows.Input.Key.Escape:

                    _popupProperties.IsOpen = false;
                    _expression.Focus();
                    e.Handled = true;

                    break;
            }
        }


        private string GetExpression()
        {
            string exp = _expression.Text.Trim();
            exp = exp.Replace("this.", "");
            return exp;
        }

        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            string value = result.Text;
            string propertyPath = GetExpression();

            try
            {
                ReflectionHelper.SetObjectPropertyValue(_pdo, propertyPath, value);
                _pdo.SaveAll();
            }
            catch (Exception ex)
            {
                string errorMessage = "Failed to save value to requested property path. " +
                        propertyPath + " to value \"" + value + "\"" +
                        "\r\nException: " + ex.ToString();

                MessageBox.Show(errorMessage);
            }


        }
        private void evaluateBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                result.Text = PDOExpressionEvaluator.Evaluate(_pdo, GetExpression());
                error.Text = string.Empty;
            }
            catch (Exception ex)
            {
                result.Text = "<error>";
                error.Text = ex.ToString();
            }
        }


        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        #endregion

    }
}
